package cn.lingyangwl.agile.member.listener;

import cn.lingyangwl.agile.member.model.mq.MemberUserDeleteMQ;
import cn.lingyangwl.agile.member.service.AccountDetailService;
import cn.lingyangwl.framework.mq.base.manager.MqManager;
import cn.lingyangwl.framework.tool.core.exception.BizException;
import com.alibaba.fastjson2.JSON;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author shenguangyang
 */
@Slf4j
@Component
@RabbitListener(bindings = {
        @QueueBinding(
                value = @Queue(value = MemberUserDeleteMQ.QUEUE, durable = "true"), key = MemberUserDeleteMQ.KEY,
                exchange = @Exchange(value = MemberUserDeleteMQ.EXCHANGE, type = ExchangeTypes.TOPIC))
})
public class MemberUserDeleterListener {
    @Resource
    private MqManager mqManager;
    @Resource
    private AccountDetailService accountDetailService;

    @RabbitHandler
    public void onMessage(String data, Channel channel, Message message) throws Exception {
        try {
            MemberUserDeleteMQ.MsgPayload msgPayload = MemberUserDeleteMQ.parse(data, MemberUserDeleteMQ.MsgPayload.class);
            // 判断是否重复消费
            if (mqManager.isConsumed(msgPayload.getMsgId())) {
                log.warn("message {} are repeatedly consumed, do not perform business", msgPayload.getMsgId());
                return;
            }

            // 删除会员账户记录
            accountDetailService.deleteByUserId(msgPayload.getUserId());

            mqManager.markConsumed(msgPayload.getMsgId());
            log.info("消费成功: {}", JSON.toJSONString(data));
        } catch (Exception e) {
            log.error("消费失败: {}, msg: {}", e.getMessage(), JSON.toJSONString(data));
            if (e instanceof NullPointerException) {
                log.error("error: ", e);
            } else if (e instanceof BizException) {
                throw e;
            }
            throw new BizException(-1, "mq消费错误");
        }
    }
}
